package com.hd.trans.ui.activity

import android.Manifest
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.view.animation.Animation
import android.view.animation.TranslateAnimation
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.bumptech.glide.Glide
import com.hd.trans.R
import com.hd.trans.TranslationInterior
import com.hd.trans.binding.visible
import com.hd.trans.databinding.ActivityFilesHomeBinding
import com.hd.trans.db.DataBaseMgr
import com.hd.trans.db.bean.HuDunLanguage
import com.hd.trans.db.bean.MediaItem
import com.hd.trans.db.bean.TransitionType
import com.hd.trans.extension.isVideo
import com.hd.trans.extension.observe
import com.hd.trans.files.aty.MediaAlbumActivity
import com.hd.trans.files.aty.PickingFileActivity
import com.hd.trans.files.bean.MediaOptions
import com.hd.trans.framework.dialog.LanguageDialog
import com.hd.trans.framework.dialog.LanguageDialogType
import com.hd.trans.limit4Use.LimitUseListener
import com.hd.trans.network.PreferenceMgr
import com.hd.trans.ui.base.AppContextProvider
import com.hd.trans.ui.base.BaseActivity
import com.hd.trans.ui.model.FileTranslateModel
import com.hd.trans.utils.Constant
import com.hd.trans.utils.FileUtils
import com.hd.trans.utils.FileUtilsKotlin
import com.hd.trans.utils.PermissionCallback
import com.hd.trans.utils.ToastUtils
import com.hd.trans.utils.TrackerForTrans

/**
 * 文档翻译
 */
class FilesHomeActivity : BaseActivity(), View.OnClickListener {
    private var twoWay: Boolean = false
    private lateinit var mDataModel: FileTranslateModel
    private var mFilePath: String? = null
    private lateinit var mDataBinding: ActivityFilesHomeBinding
    override fun getLayoutId(): Int {
        return R.layout.activity_files_home
    }

    override fun initViewsAndEvents(savedInstanceState: Bundle?) {
        //视图埋点
        val tracker = when(transType){
            TransitionType.DOCUMENT -> {
                "${TrackerForTrans.FILE_TRANS}${TrackerForTrans.SY}"
            }
            TransitionType.VIDEO -> {
                "${TrackerForTrans.VIDEO}${TrackerForTrans.SY}"
            }
            TransitionType.AUDIO -> {
                "${TrackerForTrans.AUDIO}${TrackerForTrans.SY}"
            }
            else -> "${TrackerForTrans.FILE_TRANS}${TrackerForTrans.SY}"
        }
        TranslationInterior.getTrackerListener().view(tracker)
        mDataBinding = DataBindingUtil.setContentView(this, R.layout.activity_files_home)
        mDataModel = ViewModelProvider(this).get(FileTranslateModel::class.java)
        initView()
        initData()
    }

    private fun initView() {
        mDataBinding.getFiles.text = when (transType) {
            TransitionType.VIDEO -> {
                getString(R.string.trans_video)
            }
            TransitionType.AUDIO -> {
                getString(R.string.trans_audio)
            }
            else -> {
                getString(R.string.trans_file)
            }
        }
        mDataBinding.title.back.setOnClickListener(this)
        mDataBinding.getFiles.setOnClickListener(this)
        mDataBinding.btnTranslate.setOnClickListener(this)
        mDataBinding.btnChooseAgain.setOnClickListener(this)
        mDataBinding.title.leftBt.setOnClickListener(this)
        mDataBinding.title.rightBt.setOnClickListener(this)
        mDataBinding.title.iconExchange.setOnClickListener(this)
    }

    private fun initData() {
        /**
         *  监听页面数据变化(语言改变，状态改变)
         */
        observe(mDataModel.languageFrom) {
            if (it != null) {
                mDataBinding.title.tvFrom.text = it.name
            }
        }
        observe(mDataModel.languageTo) {
            if (it != null) {
                dualIdentityLang(it)
                mDataBinding.title.tvTo.text = it.name
            }
        }

        val fromLangName = PreferenceMgr.getInstance().translatePreference.fileFromLanguage
        val toLangName = PreferenceMgr.getInstance().translatePreference.fileToLanguage
        mDataModel.setLanguageFrom(DataBaseMgr.getInstance().getLanguageByName(fromLangName))
        mDataModel.setLanguageTo(DataBaseMgr.getInstance().getLanguageByName(toLangName))

    }

    private fun dualIdentityLang(toLang: HuDunLanguage){
        twoWay = if(!TextUtils.isEmpty(toLang.fileRecognitionCode)){
            mDataBinding.title.iconExchange.setImageResource(R.mipmap.icon_change)
            true
        }else{
            mDataBinding.title.iconExchange.setImageResource(R.mipmap.icon_trans_dx)
            false
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mDataModel.languageFrom.removeObservers(this)
        mDataModel.languageTo.removeObservers(this)
    }

    override fun onClick(view: View) {
        when(view){
            //返回
            mDataBinding.title.back -> {
                finish()
            }
            //选择文件
            mDataBinding.getFiles, mDataBinding.btnChooseAgain -> {
                when(transType){
                    TransitionType.DOCUMENT -> {
                        val permissions = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                            arrayOf(Manifest.permission.MANAGE_EXTERNAL_STORAGE)
                        } else {
                            arrayOf(
                                Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE
                            )
                        }

                        checkPermissionAndStart(permissions,
                            PermissionCallback {
                                val intent = Intent(this, PickingFileActivity::class.java)
                                intent.putExtra(Constant.EXTRA_TRANSLATION_TYPE, transType)
                                startActivity(intent)
                            })
                    }
                    TransitionType.VIDEO -> {
                        val permissions = arrayOf(
                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.READ_EXTERNAL_STORAGE
                        )

                        checkPermissionAndStart(permissions,
                            PermissionCallback {
                                val options: MediaOptions = MediaOptions.build(100)
                                    .setMax(1)
                                    .setMin(1)
                                    .setMediaType(MediaOptions.TYPE_VIDEO)
                                val intent = Intent(this, MediaAlbumActivity::class.java)
                                intent.putExtra(MediaAlbumActivity.TAG_MEDIA_OPTIONS, options)
                                startActivityForResult(intent, TransitionType.VIDEO)
                            })
                    }
                    TransitionType.AUDIO -> {
                        val permissions = arrayOf(
                            Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.READ_EXTERNAL_STORAGE
                        )

                        checkPermissionAndStart(permissions,
                            PermissionCallback {
                                val intent = Intent(this, PickingFileActivity::class.java)
                                intent.putExtra(Constant.EXTRA_TRANSLATION_TYPE, transType)
                                startActivity(intent)
                            })
                    }
                }
            }
            //开始翻译
            mDataBinding.btnTranslate -> {
                mFilePath?.let {
//                    if(transType == TransitionType.DOCUMENT){//文档翻译
//                        mDataModel.executeTrans(it)
//                    }else if (transType == TransitionType.VIDEO){//视频翻译
//                        //
//                        mDataModel.executeTranslateDocument(AppContextProvider.getContext().cacheDir.absolutePath + "/文档翻译.txt")
//                    }
                    mDataModel.executeTrans(AppContextProvider.getContext().cacheDir.absolutePath + "/文档翻译.txt")
                    //mDataModel.executeTranslateDocument(AppContextProvider.getContext().cacheDir.absolutePath + "/文档翻译.txt")
                }
            }
            //选择语言
            mDataBinding.title.leftBt, mDataBinding.title.rightBt -> {
                showSelectLanguageDialog(view == mDataBinding.title.leftBt)
            }
            //交换语言
            mDataBinding.title.iconExchange -> {
                showTranslateAnimation()
            }
        }
    }

    private fun checkPermissionAndStart(permissions: Array<String>, callback: PermissionCallback) {
        permissionUtil.checkIsHavePermission(this, permissions, callback)
    }

    @Deprecated("Deprecated in Java")
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == TransitionType.VIDEO && resultCode == RESULT_OK) {
            if (data?.hasExtra(MediaAlbumActivity.TAG_RESULT) == false) {
                return
            }
            val list: ArrayList<MediaItem>? = data?.getParcelableArrayListExtra(MediaAlbumActivity.TAG_RESULT)
            if (list?.size == 0) {
                return
            }
            list?.let {
                if(it.size > 0){
                    val filePath = list[0].path
                    if (!TextUtils.isEmpty(filePath)) {
                        //返回视频路径
                        changeToTransLayout(filePath)
                    }
                }
            }

        }
        super.onActivityResult(requestCode, resultCode, data)
    }

    private fun changeToTransLayout(filePath: String) {
        mFilePath = filePath
        mDataBinding.nullDataLayout.visible = false
        mDataBinding.dataLayout.visible = true
        mDataBinding.fileName.text = FileUtils.getFileNameByPath(filePath)

        if(filePath.isVideo()){
            Glide.with(mDataBinding.fileIcon)
                .load(filePath)
                .override(600, 600)
                .placeholder(R.mipmap.ic_doc_default)
                .error(R.mipmap.ic_doc_default)
                .into(mDataBinding.fileIcon)
        }else{
            mDataBinding.fileIcon.setImageResource(FileUtilsKotlin.getFileIcon(filePath))
        }
    }


    /**选择语言弹框*/
    private fun showSelectLanguageDialog(isFrom: Boolean) {
        val dialog = LanguageDialog(
            mDataModel.languageFrom.value!!,
            mDataModel.languageTo.value!!,
            isFrom, LanguageDialogType.FILE, LanguageDialogType.TO_FILE_FILTRATION)
        dialog.show(supportFragmentManager, "LanguageDialog")
        dialog.setOnLanguageChangedListener(object : LanguageDialog.OnLanguageChangedListener{
            override fun onLanguageChanged(
                fromLanguage: HuDunLanguage,
                toLanguage: HuDunLanguage,
                selectedLanguage: HuDunLanguage,
            ) {
                mDataModel.setLanguageFrom(fromLanguage)
                PreferenceMgr.getInstance().translatePreference
                    .saveFileFromLanguage(fromLanguage.name)
                mDataModel.setLanguageTo(toLanguage)
                PreferenceMgr.getInstance().translatePreference
                    .saveFileToLanguage(toLanguage.name)
            }

        })
    }

    /**
     * 互换语种动画
     */
    private fun showTranslateAnimation() {
        if(!twoWay){
            ToastUtils.showNormal("${mDataModel.languageTo.value?.name}暂不支持双向翻译")
            return
        }
        if ("自动检测" == mDataModel.languageFrom.value?.name) {
            return
        }
        val ta1 = TranslateAnimation(0f, (mDataBinding.title.leftBt.width + mDataBinding.title.iconExchange.width).toFloat(), 0f, 0f).apply {
            duration = 600
            fillAfter = true
        }
        mDataBinding.title.leftBt.startAnimation(ta1)
        mDataBinding.title.leftBt.bringToFront()
        val ta2 = TranslateAnimation(0f, (-mDataBinding.title.rightBt.width - mDataBinding.title.iconExchange.width).toFloat(), 0f, 0f).apply {
            duration = 600
            fillAfter = true
        }
        mDataBinding.title.rightBt.startAnimation(ta2)
        mDataBinding.title.rightBt.bringToFront()
        ta1.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationStart(animation: Animation) {}
            override fun onAnimationEnd(animation: Animation) {
                val from = mDataModel.languageFrom.value
                val to = mDataModel.languageTo.value
                PreferenceMgr.getInstance().translatePreference.saveFileFromLanguage(to?.name)
                PreferenceMgr.getInstance().translatePreference.saveFileToLanguage(from?.name)
                mDataModel.setLanguageFrom(to)
                mDataModel.setLanguageTo(from)
                animation.cancel()
            }

            override fun onAnimationRepeat(animation: Animation) {}
        })
        ta2.setAnimationListener(object : Animation.AnimationListener {
            override fun onAnimationStart(animation: Animation) {}
            override fun onAnimationEnd(animation: Animation) {
                animation.cancel()
            }

            override fun onAnimationRepeat(animation: Animation) {}
        })
    }

    companion object {
        private var limitListener: LimitUseListener? = null
        private var transType: Int = TransitionType.DOCUMENT
        //open入口
        @JvmStatic
        fun openDocument(context: Context, listener: LimitUseListener?) {
            limitListener = listener
            transType = TransitionType.DOCUMENT
            val intent = Intent(context, FilesHomeActivity::class.java)
            context.startActivity(intent)
        }

        @JvmStatic
        fun openAudio(context: Context, listener: LimitUseListener?) {
            limitListener = listener
            transType = TransitionType.AUDIO
            val intent = Intent(context, FilesHomeActivity::class.java)
            context.startActivity(intent)
        }

        @JvmStatic
        fun openVideo(context: Context, listener: LimitUseListener?) {
            limitListener = listener
            transType = TransitionType.VIDEO
            val intent = Intent(context, FilesHomeActivity::class.java)
            context.startActivity(intent)
        }
    }
}